<template>
  <div
    class="chart-box"
    style="width: 100%; height: 100%"
    :style="{ backgroundColor: widgetOptions.setup.backgroundColor }"
  >
    <div v-if="!chartStatus" ref="chartRef" style="width: 100%; height: 100%"></div>
    <ChartEmpty v-if="chartStatus" :chartStatus="chartStatus" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { mapper } from '../constants'
import { useTools } from '../../hooks/useTools'
import { useSignalView } from '../../hooks/useSignalView'
import ChartEmpty from '../../components/chartEmpty.vue'

// 接收父组件传入的值
const props = defineProps({
  widgetOptions: {
    type: Object as PropType<Record<string, any>>, // 或更具体的类型
    required: true
  },
  isPreview: {
    type: Boolean,
    default: false
  }
})

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null
const chartData = ref<any>(null)

const { toRgba } = useTools()
const mockDataUrl = '/mockdata/realtime/powerSpectrum.json'

const initChart = () => {
  if (chartRef.value) {
    // 初始化实例
    myChart = echarts.init(chartRef.value)
  }
}

// 更新配置
const updateOptions = () => {
  if (!chartData.value) return
  const { signalName, startTime, value, extra } = chartData.value
  const signalLabel = mapper[signalName] || ''
  //大数据量时，使用折线图
  const isLarge = (value) => {
    return value?.length > 400
  }
  const large = isLarge(value)

  const series = [
    {
      name: name,
      type: large ? 'line' : 'bar',
      data: value,
      label: {
        show: !large,
        position: 'top',
        formatter: function (params) {
          const { data } = params
          return data[1].toFixed(2)
        }
      },
      smooth: false,
      showSymbol: false,
      itemStyle: {
        color: function (param) {
          return props.widgetOptions.setup.barColor
          // return extra?.highLight?.includes(param.dataIndex)
          //   ? props.widgetOptions.setup.barColor
          //   : props.widgetOptions.setup.barColor2
        },
        width: 5
      },
      lineStyle: {
        width: props.widgetOptions.setup.lineWidth,
        color: props.widgetOptions.setup.lineColor
      },
      areaStyle: props.widgetOptions.setup.areaStyle
        ? {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: props.widgetOptions.setup.lineColor
              },
              {
                offset: 1,
                color: toRgba(props.widgetOptions.setup.lineColor, 0.3)
              }
            ])
          }
        : null,
      large
    }
  ]
  const option = {
    title: {
      text: `${signalLabel}`,
      subtext: `开始时间：${startTime}`,
      left: 'center',
      textStyle: {
        color: props.widgetOptions.setup.titleColor,
        fontSize: props.widgetOptions.setup.titleFontSize
      },
      subtextStyle: {
        color: props.widgetOptions.setup.subtitleColor,
        fontSize: props.widgetOptions.setup.subtitleFontSize
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: 0,
        filterMode: 'none'
      },
      {
        type: 'slider',
        xAxisIndex: 0,
        filterMode: 'none'
      }
    ],
    toolbox: {
      left: 'right',
      itemSize: 25,
      top: 20,
      feature: {
        magicType: {
          type: ['line', 'bar']
        }
      },
      iconStyle: {
        color: props.widgetOptions.setup.toolboxIconColor,
        borderColor: props.widgetOptions.setup.toolboxIconColor
      }
    },
    legend: {
      type: 'scroll',
      top: '5%',
      left: 'left',
      orient: 'vertical',
      selectedMode: 'single'
    },
    xAxis: {
      type: 'category',
      axisLine: {
        lineStyle: {
          color: props.widgetOptions.setup.xLineColor
        }
      },
      axisLabel: {
        color: props.widgetOptions.setup.xFontColor,
        fontSize: props.widgetOptions.setup.xFontSize
      }
    },
    yAxis: {
      axisLabel: {
        color: props.widgetOptions.setup.yFontColor,
        fontSize: props.widgetOptions.setup.yFontSize
      },
      splitLine: {
        show: props.widgetOptions.setup.ySplitLine,
        lineStyle: {
          color: 'rgba(255,255,255,0.2)'
        }
      }
    },
    series: series
  }

  myChart?.setOption(option)
  myChart?.resize()
}

const resolveData = (data: any) => {
  if (data && data.msgPack) {
    chartStatus.value = ''
    chartData.value = data.msgPack
    updateOptions()
  } else {
    chartStatus.value = 'noData'
    chartData.value = null
  }
}

const resolveMockData = (data: any) => {
  chartData.value = data
  updateOptions()
}

const { chartStatus, refreshData } = useSignalView(
  props.widgetOptions,
  props.isPreview,
  mockDataUrl,
  resolveData,
  resolveMockData
)

onMounted(() => {
  initChart()
  refreshData()
})

// 如果父组件传入的 props.value 改变，需要更新折线图颜色等
watch(
  () => props.widgetOptions,
  () => {
    if (myChart) {
      updateOptions()
    }
  },
  { immediate: true, deep: true }
)

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})
</script>

<style scoped></style>
